package org.liubility.robot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.liubility.commons.dto.robot.RobotMsgResult;
import org.liubility.robot.domain.entity.RobotPostOrder;
import org.liubility.commons.http.response.normal.Result;
import org.liubility.commons.json.JsonUtils;
import org.liubility.robot.mappers.PostOrderMapper;
import org.liubility.robot.service.PostOrderManagerService;
import org.liubility.robot.untils.MessageBuild;
import org.liubility.robot.untils.PostOrderListCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: Jdragon
 * @email: 1061917196@qq.com
 * @Date: 2020.10.24 22:05
 * @Description:
 */

@Service
public class PostOrderManagerServiceImpl extends ServiceImpl<PostOrderMapper, RobotPostOrder> implements PostOrderManagerService {
    @Autowired
    private PostOrderListCache postOrderListCache;

    @Override
    public String getOrderListStr() {
        StringBuilder postOrderListStr = new StringBuilder();
        List<RobotPostOrder> robotPostOrderList = this.list();
        for (RobotPostOrder robotPostOrder : robotPostOrderList) {
            postOrderListStr
                    .append(robotPostOrder.getOrderStr()).append("\t")
                    .append(robotPostOrder.getRemark()).append("\n");
        }
        return postOrderListStr.toString();
    }

    @Override
    public String getRegistrationTemplate() {
        return "注册模板：" + JsonUtils.object2StrIncludeNull(new RobotPostOrder()) + "\n" +
                "你的服务接受参数：" + JsonUtils.object2StrIncludeNull(new RobotMsgResult()) + "\n" +
                "你的接口返回参数" + JsonUtils.object2StrIncludeNull(Result.success(new RobotMsgResult()));
    }

    @Override
    public String register(Long register, RobotPostOrder robotPostOrder) {
        RobotMsgResult result = PostOrderHandlerApi.robotHandle(robotPostOrder.getUrl(), robotPostOrder.getRequest(), robotPostOrder
                .getParam(), MessageBuild.unpackMessage(register, "test"));
        if (result != null && "success".equals(result.getMessage())) {
            if (robotPostOrder.insert()) {
                if (postOrderListCache.refresh()) {
                    return "注册成功，刷新成功，能用到这个新指令了";
                } else {
                    return "注册成功，但刷新失败，你可能用不到这个新指令";
                }
            } else {
                return "注册服务异常，注册失败";
            }
        } else {
            return "指令提供接口异常";
        }
    }

    @Override
    public String getHelp() {
        return "#指令刷新\n" +
                "#指令注册列表\n" +
                "#指令注册模板\n" +
                "#指令注册\n";
    }
}
